var quotes=new Array();
getData(); // populate quotes

	
var mode = Titanium.App.Properties.getString("mode");
mode = mode=='multiple' ? 'multiple' : 'boolean';
// mode = mode=='boolean' ? 'boolean' : 'multiple';

var author = '......';
var quote = '......';
var suggestion1 = null;
var suggestion2 = null;
var suggestion3 = null;
var labelAuthor = null;
var labelQuote = null;
var labelSuggestion = null;
var buttonYes = null;
var buttonNo = null;
var buttonNext = null;
var optionPrefix = ' - ';
var suggestionPrefix = '';
var suggestionSuffix = '?';
var answerOptions = new Array();
var labelHeading = '';
var switchToMultipleTxt = 'Switch to Multiple Choice';
var switchToYesNoTxt = 'Switch to Yes/No Questions';
// var colorArray = ["#f9058f","#4c706d","#333366","#666666", "#663366"];
// var dominantColor = colorArray[Math.floor(Math.random() * colorArray.length)];


var dominantColor = '#666666'; 
var dominantColor = '#8772cc';  // blueish
var dominantColor = '#699e2f' ; // green
var dominantColor = '#f9058f'; // magenta

var standardFontSize = '18dp' ;
var largeFontSize = '20dp' ;

// var pWidth = Ti.Platform.displayCaps.platformWidth;
// var pHeight = Ti.Platform.displayCaps.platformHeight;
// var heightCorrection = pHeight>=600 ? (pHeight - 600)   : 0 ; // to do
// Ti.API.info('screen height is '+ pHeight);	
// standardFontSize = pHeight>=600 ? 32 : 20 ;
	
Titanium.UI.orientation = Titanium.UI.PORTRAIT;
Titanium.UI.setBackgroundColor(dominantColor);

//Set window background
 Titanium.UI.setBackgroundImage('/images/butterflies.png');
 

function AppTabGroup() {
	
		
	//declare module dependencies
	var AppWindow = require('ui/AppWindow');
	
	//create module instance
	var self = Ti.UI.createTabGroup();
	
	//create app tabs
	var win1 = new AppWindow('Quotes'),
		win2 = new AppWindow('Settings');
	
	
	var tab1 = Ti.UI.createTab({
		title: 'Quotes',
		icon: '/images/tab_icon_quote.png',	
		window: win1
	});
	win1.containingTab = tab1;
	
	
	

	
	Titanium.App.Properties.setInt("counter", 0 ); // initialize counter of quotes
	
	author = quotes[0][0];
	quote = quotes[0][1];
	suggestion1 = quotes[0][2];
	suggestion2 = quotes[0][3];
	suggestion3 = quotes[0][4];
	
//	var botomH = 50 + heightCorrection;
	
	var scrollView1 = Titanium.UI.createScrollView({
    	contentWidth:'auto',
  //  	backgroundImage:'/images/butterflies.png',
    	top:'35dp',
        bottom: '180dp',	
        left: 10,
        right: 10,
   	    backgroundColor: dominantColor,
	    borderColor: dominantColor,
		borderRadius: 10,
	    borderWidth: 10, 	
    	showVerticalScrollIndicator:true,
    	showHorizontalScrollIndicator:true
		});
		
		
	labelHeading = Titanium.UI.createLabel({
		color:'#666666',
		text: 'Who Said It:',
		font:{fontSize:  standardFontSize, FontFamily: 'Palatino'}, // fontSize:22,
		textAlign:'left',
		left: 10,
		right: 10,
		top: '3dp',    		     
		width:'auto'
	});	
		
	labelQuote = Titanium.UI.createLabel({
		color:'#ffffff',
		text: '"'+quote+'"',
		font:{fontSize:  standardFontSize, fontFamily: 'Palatino'}, // fontSize:22,
		textAlign:'left',
		left: 10,
		right: 10,
		top: '10dp',
	    backgroundColor:dominantColor, //  8305f9
	    borderColor: dominantColor,
		borderRadius: 16,
	    borderWidth: 10,
	    marginLeft: 20,
	   	marginTop: 120,
	   	marginRight: 20,
	   	marginBottom: 20,	    	     
		width:'auto'
	});

	win1.add(labelHeading);
	scrollView1.add(labelQuote);
	win1.add(scrollView1);
	
	
//	var botomH =  botomH - 45;	
	labelAuthor = Titanium.UI.createLabel({
		color:dominantColor,	
		font:{fontSize:standardFontSize},	
	    backgroundColor:'#ffffff',
	    borderColor: '#ffffff',
		borderRadius: 10,
	    borderWidth: 14,
		text: author,
		right:30,
		textAlign:'right',
		width:'auto',
		bottom: '120dp',
	    visible:false,
	    opacity:0.0 
	});
	win1.add(labelAuthor);
	
	
    var bBooleanControlsVisible = mode=='boolean' ? true : false;
    var bMultiControlsVisible = mode!='boolean' ? true : false;
  
   // boolean controls

		labelSuggestion = Titanium.UI.createLabel({
			color:'#062a04',
			font:{fontSize:standardFontSize},	
			text: suggestionPrefix + suggestion2+suggestionSuffix, // or suggestion 2, or suggestion 3
			textAlign:'left',
			width:'auto',
			bottom: '110dp',
		    visible: bBooleanControlsVisible
		});
		win1.add(labelSuggestion);	
		
		var YesNoFontSize = largeFontSize;
		buttonYes = Titanium.UI.createButton({ 
			title: 'Yes' ,
			font:{fontSize:YesNoFontSize},	
		    backgroundColor:'#6da134',
			color:'#ffffff',
			borderRadius: 6,
			bottom: 20,
			left: 30,
		    visible: bBooleanControlsVisible						
		}); 
		
		buttonNo = Titanium.UI.createButton({ 
			title: 'No' ,
			font:{fontSize:YesNoFontSize},	
	    	backgroundColor:'#f90544',
			color:'#ffffff',
			borderRadius: 6,
			bottom: 20,
			right: 30,
			visible: bBooleanControlsVisible
		}); 	

		win1.add(buttonYes);		
		win1.add(buttonNo);

				
		labelSuggestion.addEventListener('click', showAnswer);
		buttonYes.addEventListener('click', checkAnswerForYes);
		buttonNo.addEventListener('click', checkAnswerForNo);
		
	   // boolean controls end
		
		
			
	   // multi controls start
	   
	   	answerOptions[0] = Titanium.UI.createLabel({
			font:{fontSize:standardFontSize},	
			text: optionPrefix + suggestion1,
			textAlign:'left',
			width:'auto',
			bottom: '120dp',
			id: 'OptionOne',				
			shadowColor:'#aaa', 
	    	backgroundColor:'#666666',
	    	borderColor: '#666666',
	    	color:'#ffffff',
			borderRadius: 10,
	   	    borderWidth: 10, 	
	   	    left: '20dp',
	    	right: '20dp',
		    visible: bMultiControlsVisible
		});
		win1.add(answerOptions[0]);	
		answerOptions[0].addEventListener('click', checkMultipleChoiceAnswer);
		
		answerOptions[1] = Titanium.UI.createLabel({
			font:{fontSize:standardFontSize},	
			text: optionPrefix + suggestion2,
			textAlign:'left',
			width:'auto',
			bottom: '70dp',
			id: 'OptionTwo',		
			shadowColor:'#aaa', 
	    	backgroundColor:'#666666',
	    	borderColor: '#666666',
	    	color:'#ffffff',
			borderRadius: 10,
	   	    borderWidth: 10, 	
	   	    left: '20dp',
	    	right: '20dp',			
			visible: bMultiControlsVisible
		});
		win1.add(answerOptions[1]);	
		answerOptions[1].addEventListener('click', checkMultipleChoiceAnswer);		
		
		answerOptions[2] = Titanium.UI.createLabel({
			font:{fontSize:standardFontSize},	
			text: optionPrefix + suggestion3,
			textAlign:'left',
			width:'auto',
			bottom: '20dp',
			id: 'OptionThree',		
			shadowColor:'#aaa', 
	    	backgroundColor:'#666666',
	    	borderColor: '#666666',
	    	color:'#ffffff',
			borderRadius: 10,
	   	    borderWidth: 10, 	
	   	    left: '20dp',
	    	right: '20dp',		
		    visible: bMultiControlsVisible
		});
		win1.add(answerOptions[2]);	
		answerOptions[2].addEventListener('click', checkMultipleChoiceAnswer);			
					
					
	   
	   // multi controls end	
		
		 
	
	
	

	buttonNext = Titanium.UI.createButton({
	//	height:44,
		width:'auto',		
		title:'Next Quote',
		id: 'nextBtn',
		bottom:'10dp',
		left:'30dp',	
		right:'30dp',		
	    visible: false	
	});
	win1.add(buttonNext);
		
	
	

	buttonNext.addEventListener('click', getNextQuote);
	
	

	// Second Tab starts here	
		
	
	var tab2 = Ti.UI.createTab({
		title: 'Settings',
		icon: '/images/tab_icon_settings.png',
		window: win2
	});
	win2.containingTab = tab2;


	
	self.addTab(tab1);
	self.addTab(tab2);




//tab 2
//var logoImg=Titanium.Filesystem.getFile('../logo.png');
/*
var logoImg=Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'logo.png');
var logo=Titanium.UI.createImageView({
    image:logoImg,
    top:10,
    width: 100,
    height: 100
});
win2.add(logo);
*/
var aboutText='"Famous Quote Quiz" is another great brain teaser that makes you remember famous quotes by great people.\n\n'; 
aboutText+='The application can run in two modes: "'+ switchToYesNoTxt.replace('Switch to ','') +'" and "'+ switchToMultipleTxt.replace('Switch to ','') +'".\n\n';
aboutText+='Click the button below to switch between modes and then view the other tab.';
/*
aboutText+='Current mode is: '; 
if (mode=='boolean')
{
	aboutText+='Yes/No questions.';
} else{
	aboutText+='Multiple choice questions.';
}
*/

var labelAbout = Titanium.UI.createLabel({
	color:'#666666',
	text: aboutText,
//	font:{fontFamily:'Helvetica Neue'}, // fontSize:20,
	font:{fontSize:standardFontSize},		
	textAlign:'left',
	left: 10,
	top: 10,	
	width:'auto'
});

var scrollView2 = Titanium.UI.createScrollView({
    contentWidth:'auto',
    contentHeight:'auto',
    top:20,
    bottom: 110,
   	backgroundColor: '#ffffff',    
   	borderRadius: 10,
   	opacity: 0.5,
   	left: 10,
   	right: 10,
    showVerticalScrollIndicator:true,
    showHorizontalScrollIndicatSor:true
});


var switchTitle = (mode=='boolean')? ' '+switchToMultipleTxt+' ' : ' '+switchToYesNoTxt+' ' ;
var switchId = (mode=='boolean')?'multiple':'boolean' ;

var	buttonSwitchMode = Titanium.UI.createButton({
	//  height:44,
	//	width:200,
		width: 'auto',
		left:'30dp',	
		right:'30dp',		
		title: switchTitle,
		id: switchId,
		bottom:30,
	    visible: true	
});

scrollView2.add(labelAbout);


buttonSwitchMode.addEventListener('click', switchMode);

win2.add(scrollView2);
win2.add(buttonSwitchMode);

/*
var	buttonGetData = Titanium.UI.createButton({
		height:24,
		width:200,
		title: 'Get Data asap ',
		bottom: 0,
	    visible: true	
});
scrollView2.add(buttonGetData);	
buttonGetData.addEventListener('click', getData);
*/

function switchMode(e)
{
	
	
	mode=this.id;
	Titanium.App.Properties.setString("mode", mode);
	
	
	switch(mode)
	{
	 case 'multiple':

		labelSuggestion.hide();
		buttonYes.hide();
		buttonNo.hide();

 		labelSuggestion.animate({
		   opacity:0.0,
		   duration:10
		  }); 
 		buttonYes.animate({
		   opacity:0.0,
		   duration:10
		  }); 
 		buttonNo.animate({
		   opacity:0.0,
		   duration:10
		  }); 		  
		  		  
		answerOptions[0].show();
		answerOptions[1].show();
	    answerOptions[2].show();

	    buttonSwitchMode.title = switchToYesNoTxt;
	    buttonSwitchMode.id = 'boolean';
	    	    
	 break;

	case 'boolean':
	default:
	 		
		answerOptions[0].hide();
		answerOptions[1].hide();
	    answerOptions[2].hide();	
	    	
 		answerOptions[0].animate({
		   opacity:0.0,
		   duration:10
		  }); 		  
 		answerOptions[1].animate({
		   opacity:0.0,
		   duration:10
		  });		  		
 		answerOptions[2].animate({
		   opacity:0.0,
		   duration:10
		  });		  			    	
	    	
		labelSuggestion.show();
		buttonYes.show();
		buttonNo.show();

	    buttonSwitchMode.title = switchToMultipleTxt;
	    buttonSwitchMode.id = 'multiple';

	 break;

	}
		

	win1.focus();
	getNextQuote();
	Ti.API.info('Mode switched to '+ mode +' successfully.');
	// alert('Mode switched successfully.');
	
		
}	
	




// JS fuinction library 
	
	function checkMultipleChoiceAnswer(e)
	{
		var thisValue = this.text;		
		thisValue = thisValue.replace(optionPrefix,'');

		if ( thisValue == labelAuthor.text)
		{
			alert('Correct! The right answer is '+labelAuthor.text);
		} else {
			alert('Wrong! The right answer is '+labelAuthor.text);
		}	
		
		for (var i=0; i<3; i++)
		{
			thisValue = answerOptions[i].text;
			thisValue = thisValue.replace(optionPrefix,'');

			if (thisValue==labelAuthor.text)
			{
				answerOptions[i].backgroundColor=dominantColor;
				answerOptions[i].borderColor=dominantColor;
			}
		}		
		
		setTimeout(function(){showAnswer(e)}, 1000);
		
		
		setTimeout(function(){
			for (var i=0; i<3; i++)
			{
				answerOptions[i].backgroundColor='#666666';
				answerOptions[i].borderColor='#666666';		
			}	

		}, 1000);
		
	}
	


   
    
    	
	
    function getNextQuote()
    {
      var count = 	Titanium.App.Properties.getInt("counter");
      count++;    
      if (count>=quotes.length || quotes[count].length==0 )
      {
      	count=0;
      }
      Titanium.App.Properties.setInt("counter", count );
   		

	  labelAuthor.text = quotes[count][0];	
	  labelQuote.text = '"'+quotes[count][1]+'"';
	  		
 	//  var q = labelQuote.text; 
	//  var a = labelAuthor.text; 
	//  labelQuote.text = q+"\n"+a; 
	  
	  
  	  labelAuthor.animate({
	   opacity:0.1,
	   duration:500
	  });
  	  buttonNext.animate({
	   opacity:0.0,
	   duration:500
	  }); 	
	  
	  if (mode=='boolean')
	  {	  
	  	
	      labelSuggestion.text = suggestionPrefix + quotes[count][2]+suggestionSuffix;
		
		  labelSuggestion.animate({
		   opacity:1.0,
		   duration:500
		  }); 
		  buttonYes.animate({
		   opacity:1.0,
		   duration:500
		  }); 
		  buttonNo.animate({
		   opacity:1.0,
		   duration:500
		  }); 
	  } else {
	  	
	      answerOptions[0].text =  optionPrefix + quotes[count][2];
	      answerOptions[1].text =  optionPrefix + quotes[count][3];
	  	  answerOptions[2].text =  optionPrefix + quotes[count][4];
	  	          		
	  	  answerOptions[0].animate({
		   opacity:1.0,
		   duration:500
		  }); 
		  answerOptions[1].animate({
		   opacity:1.0,
		   duration:500
		  }); 
		  answerOptions[2].animate({
		   opacity:1.0,
		   duration:500
		  }); 	  
	  	
	  }


  
    }



	function checkAnswerForYes(e)
	{
	
	    var suggestion = labelSuggestion.text;
	    suggestion = suggestion.replace(suggestionPrefix,'');
	    suggestion = suggestion.replace(suggestionSuffix,'');	    
		if ( suggestion == labelAuthor.text)
		{
			alert('Correct! The right answer is '+labelAuthor.text);
		} else {
			alert('Wrong! The right answer is '+labelAuthor.text);
		}
	
		showAnswer(e);
	
	}


	function checkAnswerForNo(e)
	{

	    var suggestion = labelSuggestion.text;
	    suggestion = suggestion.replace(suggestionPrefix,'');
	    suggestion = suggestion.replace(suggestionSuffix,'');	
	    
		if ( suggestion != labelAuthor.text)
		{
			alert('Correct! The right answer is '+labelAuthor.text);
		} else {
			alert('Wrong! The right answer is '+labelAuthor.text);
		}
	
	
		showAnswer(e);

	}



	function showAnswer(e)
	{
	  labelAuthor.animate({
	   opacity:1.0,
	   duration:500
	  });
	  
	  if (mode=='boolean')
	  {
		  labelSuggestion.animate({
		   opacity:0.0,
		   duration:500
		  }); 
		  buttonYes.animate({
		   opacity:0.0,
		   duration:500
		  }); 
		  buttonNo.animate({
		   opacity:0.0,
		   duration:500
		  }); 
		  
	  } else {
	  	
	  	  answerOptions[0].animate({
		   opacity:0.0,
		   duration:500
		  }); 	  
	  	  answerOptions[1].animate({
		   opacity:0.0,
		   duration:500
		  }); 
	  	  answerOptions[2].animate({
		   opacity:0.0,
		   duration:500
		  }); 		  	  	  
	  }
	  
  	  buttonNext.animate({
	   opacity:1.0,
	   duration:500
	  }); 	

	}





	
	return self;
};

module.exports = AppTabGroup;











/****************** Global functions ******************/

function getData()
{
		var dataChunks = [1, 2, 3, 4, 5, 6];
		var num = dataChunks[Math.floor(Math.random() * dataChunks.length)]; // randomize
		var f = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+'data/', 'data'+num+'.xml');
		Titanium.API.info('file = ' + f);
		var contents = f.read();
		var xml = Titanium.XML.parseString(contents);
		var items = xml.documentElement.getElementsByTagName("row");
		for (var i=0; i<items.length; i++)
		{
			
			var quote = items.item(i).getElementsByTagName('quote').item(0).text;
			
			var author = items.item(i).getElementsByTagName('author').item(0).text;
			
			var suggestions = Array();
			suggestions[0] = items.item(i).getElementsByTagName('author_suggestion_one').item(0).text;
			suggestions[1] = items.item(i).getElementsByTagName('author_suggestion_two').item(0).text;
			suggestions[2] = author;
			
			fisherYates(suggestions); // shuffle
												
			quotes[i] = new Array();
			quotes[i][0] = trim(author);
			quotes[i][1] = trim(quote);
			quotes[i][2] = trim(suggestions[0]);
			quotes[i][3] = trim(suggestions[1]);
			quotes[i][4] = trim(suggestions[2]);			
																		
		}
		
		fisherYates(quotes); // shuffle

}
	
	


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}


function fisherYates ( myArray ) {// shuffle
		

	  var i = myArray.length;
	  if ( i == 0 ) return false;
	  while ( --i ) {
	     var j = Math.floor( Math.random() * ( i + 1 ) );
	     var tempi = myArray[i];
	     var tempj = myArray[j];
	     myArray[i] = tempj;
	     myArray[j] = tempi;
	   }
}






	